package com.yadang.xml;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 将xml转成List<String></>
 */
public class XmlParser {
    public static void main(String[] args) {
        try {
            // 1. 创建DocumentBuilderFactory对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 2. 创建DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 3. 加载XML文件到Document对象
            File file = new File("D:\\IDEA_Workspaces\\YadangDayDayUp\\baseKnowledge\\src\\main\\java\\com\\yadang\\xml\\1.xml");
            Document doc = builder.parse(file);
            // 4. 获取所有Record元素
            NodeList recordList = doc.getElementsByTagName("Record");
            // 5. 遍历每个Record元素，获取其内容并添加到List集合中
            List<String> recordContentList = new ArrayList<>();
            for (int i = 0; i < recordList.getLength(); i++) {
                Element recordElement = (Element) recordList.item(i);
                String recordContent = getStringFromElement(recordElement);
                recordContentList.add(recordContent);
            }
            // 输出List集合中的内容
            System.out.println(recordContentList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getStringFromElement(Element element) {
        StringBuilder sb = new StringBuilder();
        NodeList childNodes = element.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            if (childNodes.item(i).getNodeType() == Element.ELEMENT_NODE) {
                Element childElement = (Element) childNodes.item(i);
                String childContent = getStringFromElement(childElement);
                sb.append("<").append(childElement.getNodeName()).append(">");
                sb.append(childContent);
                sb.append("</").append(childElement.getNodeName()).append(">");
            }
            else if (childNodes.item(i).getNodeType() == Element.TEXT_NODE) {
                sb.append(childNodes.item(i).getTextContent());
            }
        }
        return sb.toString();
    }

}
